package com.weitu.accidentEvent.accident.controller;

import com.weitu.accessory.bean.AccessoryPackageInfo;
import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.accidentEvent.accident.entity.Accident;
import com.weitu.accidentEvent.accident.service.AccidentService;
import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.workflow.flowBusiness.constant.FlowBusinessConstants;
import com.weitu.workflow.flowManagement.entity.WorkflowReview;
import com.weitu.workflow.flowManagement.service.FlowManagementService;
import org.fireflow.engine.IProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * 事故controller
 * Created by fanyuting on 2017/5/17 0017.
 */
@Controller
@RequestMapping("accidentEvent/accident")
public class AccidentController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "accidentEvent/accident/";
    @Autowired
    private AccidentService accidentService;
    @Autowired
    private AccessoryUtilService accessoryUtilService;//附件
    @Autowired
    private FlowManagementService flowManagementService;//流程管理service
    private WorkflowReview workflowReview;

    public WorkflowReview getWorkflowReview() {
        return workflowReview;
    }

    /**
     * 跳转到事故信息列表页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String toAccidentListPage(Model model) {

        return MODULE_BATH_PATH + "list";
    }

    /**
     * 查询分页列表数据
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("queryListByParam")
    public Object queryListByParam(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        //获取前台参数
        putParametersIntoMap(map);
        Integer totalNum = this.accidentService.queryListCountByParam(map);//获取总数
        DataGridPagination pagination = DataGridPagination.getInstance(request, totalNum);
        PageView pageView = pagination.getPageView();//生成pageView分页对象
        map.put("pageView", pageView);
        List<Accident> list = this.accidentService.queryListByParam(map);
        return pagination.flushDataGridData(list);
    }

    /**
     * 跳转到事故信息简单列表页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "simpleList", method = RequestMethod.GET)
    public String toAccidentSimpleListPage(Model model) {

        return MODULE_BATH_PATH + "simpleList";
    }

    /**
     * 跳转到新增页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String toAccidentAddPage(Model model) {

        return MODULE_BATH_PATH + "add";
    }

    /**
     * 跳转到编辑列表页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "edit", method = RequestMethod.GET)
    public String toAccidentEditPage(HttpServletRequest request, Model model) {
        String businessId = request.getParameter("businessId");//业务Id
        //查询隐患信息
        Accident info = this.accidentService.queryInfoById(businessId);
        //查询该业务对应的附件信息
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(businessId);
        model.addAttribute("info", info);
        model.addAttribute("accessoryList", accessoryList);
        return MODULE_BATH_PATH + "edit";
    }

    /**
     * 跳转到详情页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "detail", method = RequestMethod.GET)
    public String toAccidentDetailPage(HttpServletRequest request, Model model) {
        String businessId = request.getParameter("businessId");//业务Id
        //查询隐患信息
        Accident info = this.accidentService.queryInfoById(businessId);
        //查询该业务对应的附件信息
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(businessId);
        model.addAttribute("info", info);
        model.addAttribute("accessoryList", accessoryList);
        return MODULE_BATH_PATH + "detail";
    }

    /**
     * 保存事故信息
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/addAccidentInfo")
    @Transactional
    public AjaxResult addAccidentInfo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap();
        getAddBasicFieldMap(map);
        String happenTime = map.get("happenTime").toString();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(happenTime);
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String yearth = calendar.get(Calendar.YEAR) + "";
        String month = (calendar.get(Calendar.MONTH) + 1) + "";
        map.put("yearth", yearth);
        map.put("month", month);
        boolean accFlag = false;
        boolean flag = this.accidentService.addInfo(map);
        if (flag) {
            accFlag = AccessoryUtil.saveAccerssoryInfo(map.get("id").toString());
        }
        if (accFlag) {
            return success("事故信息保存成功！");
        }
        return fail("事故信息保存失败！");
    }

    /**
     * 更新事故信息
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/editAccidentInfo")
    @Transactional
    public AjaxResult editAccidentInfo(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap();
        getEditBasicFieldMap(map);
        //封装年度和月份
        String happenTime = map.get("happenTime").toString();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(happenTime);
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String yearth = calendar.get(Calendar.YEAR) + "";
        String month = (calendar.get(Calendar.MONTH) + 1) + "";
        map.put("yearth", yearth);
        map.put("month", month);
        boolean accFlag = false;
        boolean flag = this.accidentService.editInfo(map);
        if (flag) {
            accFlag = AccessoryUtil.saveAccerssoryInfo(map.get("id").toString());
        }
        if (accFlag) {
            return success("事故信息保存成功！");
        }
        return fail("事故信息保存失败！");
    }

    /**
     * 删除数据
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public AjaxResult deleteAccidentInfo(HttpServletRequest request, HttpServletResponse response) {
        String businessId = this.getPara("businessId");
        boolean flag = this.accidentService.deleteInfo(businessId);
        if (flag) {
            return success("事故信息删除成功！");
        }
        return fail("事故信息删除失败！");
    }


     /*==============业务审批流程相关controller=======================*/

    /**
     * 保存并提交审批
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("addAndSubmit")
    public AjaxResult addAndSubmit(HttpServletRequest request) throws Exception {
        /*
        * 保存操作
        * */
        Map<String, Object> map = new HashMap();
        getAddBasicFieldMap(map);
        String happenTime = map.get("happenTime").toString();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(happenTime);
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String yearth = calendar.get(Calendar.YEAR) + "";
        String month = (calendar.get(Calendar.MONTH) + 1) + "";
        map.put("yearth", yearth);
        map.put("month", month);
        boolean accFlag = false;
        boolean flag = this.accidentService.addInfo(map);
        if (flag) {
            accFlag = AccessoryUtil.saveAccerssoryInfo(map.get("id").toString());
        }
        AjaxResult result = new AjaxResult();
        /*
        * 提交审批操作
        * */
        if (accFlag) {
            User crrentUser = this.getSessionUser();
            Map<String, Object> paramMap = new HashMap<String, Object>();

            //putParametersIntoMap(paramMap);
            paramMap = map;

            String businessId = paramMap.get("id").toString();//业务id
            String nextUserId = paramMap.get("nextUserId").toString();//下一环节审批人id
            //获取事故信息
            //Accident info = this.accidentService.queryInfoById(businessId);
            // LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
            //启动流程实例
            IProcessInstance processInstance = this.flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_AE_ACCIDENT, businessId, "事故信息登记", nextUserId);
            //int i=1/0;
            boolean appStateFlag = false;
            if (processInstance != null) {
                appStateFlag = this.accidentService.editAppState(businessId, "0");
            }
            if (appStateFlag) {
                result.setMessage("提交成功！");
                result.setSuccess(true);
            } else {
                result.setMessage("提交失败！");
                result.setSuccess(false);
            }
        } else {
            result.setMessage("事故信息保存失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 编辑并提交审批
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("editAndSubmit")
    public AjaxResult editAndSubmit(HttpServletRequest request) throws Exception {
        /*
        * 编辑操作
        * */
        Map<String, Object> map = new HashMap();
        getEditBasicFieldMap(map);
        //封装年度和月份
        String happenTime = map.get("happenTime").toString();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(happenTime);
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String yearth = calendar.get(Calendar.YEAR) + "";
        String month = (calendar.get(Calendar.MONTH) + 1) + "";
        map.put("yearth", yearth);
        map.put("month", month);
        boolean accFlag = false;
        boolean flag = this.accidentService.editInfo(map);
        if (flag) {
            accFlag = AccessoryUtil.saveAccerssoryInfo(map.get("id").toString());
        }
        AjaxResult result = new AjaxResult();
        /*
        * 提交审批操作
        * */
        if (accFlag) {
            User crrentUser = this.getSessionUser();
            Map<String, Object> paramMap = new HashMap<String, Object>();

            //putParametersIntoMap(paramMap);
            paramMap = map;

            String businessId = paramMap.get("id").toString();//业务id
            String nextUserId = paramMap.get("nextUserId").toString();//下一环节审批人id
            //获取事故信息
            //Accident info = this.accidentService.queryInfoById(businessId);
            // LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
            //启动流程实例
            IProcessInstance processInstance = this.flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_AE_ACCIDENT, businessId, "事故信息登记", nextUserId);
            //int i=1/0;
            boolean appStateFlag = false;
            if (processInstance != null) {
                appStateFlag = this.accidentService.editAppState(businessId, "0");
            }
            if (appStateFlag) {
                result.setMessage("提交成功！");
                result.setSuccess(true);
            } else {
                result.setMessage("提交失败！");
                result.setSuccess(false);
            }
        } else {
            result.setMessage("事故信息保存失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 提交审批
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "submitApplication", method = RequestMethod.POST)
    public AjaxResult submitApplication(HttpServletRequest request) throws Exception {
        User crrentUser = this.getSessionUser();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();
        putParametersIntoMap(paramMap);

        String businessId = paramMap.get("id").toString();//业务id
        String nextUserId = paramMap.get("nextUserId").toString();//下一环节审批人id
        //获取事故信息
        //Accident info = this.accidentService.queryInfoById(businessId);
        // LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
        //启动流程实例
        IProcessInstance processInstance = this.flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_AE_ACCIDENT, businessId, "事故信息登记", nextUserId);
        //int i=1/0;
        boolean appStateFlag = false;
        if (processInstance != null) {
            appStateFlag = this.accidentService.editAppState(businessId, "0");
        }

        if (appStateFlag) {
            result.setMessage("提交成功！");
            result.setSuccess(true);
        } else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /***
     * 跳转到信息审批页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toApplicationVerify")
    public ModelAndView toApplicationVerify(HttpServletRequest request) {
        User crrentUser = this.getSessionUser();
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //获取参数
        putParametersIntoMap(paramMap);
        String businessId = paramMap.get("businessId").toString();//获取业务id，以businessId命名
        //工作项id
        String workItemId = paramMap.get("workItemId").toString();
        //表单类型；0：只读表单；1：编辑表单
        int formType = paramMap.get("formType") != null ? Integer.parseInt(paramMap.get("formType").toString()) : 0;
        modelAndView.addObject("workItemId", workItemId);
        modelAndView.addObject("formType", formType);

        //获取意见信息
        WorkflowReview workflowReview = this.flowManagementService.queryWorkflowReviewByWorkItemId(workItemId);
        modelAndView.addObject("workflowReview", workflowReview);

        //查询事故信息
        Accident info = this.accidentService.queryInfoById(businessId);
        //查询该业务对应的附件信息
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(businessId);
        //步骤：第几步信息
        String step = request.getParameter("step");
        modelAndView.addObject("step", step);
        modelAndView.addObject("info", info);
        modelAndView.addObject("accessoryList", accessoryList);
        modelAndView.addObject("uploadUserId", crrentUser.getId());
        modelAndView.setViewName(MODULE_BATH_PATH + "verify");
        return modelAndView;
    }

    /**
     * 审批信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "verifyApplication")
    public AjaxResult verifyApplication(HttpServletRequest request) throws Exception {
        String businessId = request.getParameter("businessId");
        String workItemId = request.getParameter("workItemId");//获取工作项id
        //查询处理结果及意见
        WorkflowReview workflowReview = this.flowManagementService.getWorkflowReviewByRequest(request, "workflowReview", workItemId);
        //保存处理结果
        boolean boo = this.flowManagementService.saveWorkflowReview(workflowReview);
        //步骤：第几步信息
        String step = request.getParameter("step");
        //结束环节，继续流程向下执行
        if (boo) {
            //更改业务中的审批状态
            String result = workflowReview.getResult();
            if ("1".equals(result)) {
                if ("2".equals(step)) {
                    this.accidentService.editAppState(businessId, "1");
                }
            } else {
                if ("2".equals(step)) {
                    this.accidentService.editAppState(businessId, "-1");
                }

            }

            this.flowManagementService.workItemComplete(workItemId);
        }
        //打印工作流信息
        //System.out.println(workflowReview.getComments());

        AjaxResult result = new AjaxResult();
        if (boo) {
            result.setMessage("提交成功！");
            result.setSuccess(true);
        } else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }

}
